# apps/users/tests.py
# ------------------------------------------------------------
# 本文件专门覆盖 login.html 中使用的 4 个后端接口：
#   1. POST /users/login/           —— 登录
#   2. POST /users/                 —— 注册
#   3. GET  /users/all/             —— 找回密码第一步：列出用户名
#   4. PUT  /users/<id>/update/     —— 找回密码第二步：更新密码
# ------------------------------------------------------------

from django.urls import reverse
from rest_framework.test import APITestCase
from rest_framework import status
import uuid

from .models import User


class LoginHTMLAPITests(APITestCase):
    """
    针对 login.html 的所有接口交互编写的集成测试
    """

    def setUp(self):
        # 预置一名已存在用户：alice
        self.alice = User.objects.create(
            username='alice',
            password='alicepw',
            email='alice@mail.com',
            phone='13300000000',
            role='普通用户',
            permission_level=1
        )

    # ------------------------------------------------------------------
    # 1) /users/login/  —— 登录接口
    # ------------------------------------------------------------------

    def test_login_success(self):
        """【登录接口】用户名密码正确 → 200 & 登录成功"""
        res = self.client.post(reverse('user-login'),
                               {'username': 'alice', 'password': 'alicepw'},
                               format='json')
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(res.data['message'], '登录成功')
        self.assertEqual(res.data['user']['username'], 'alice')

    def test_login_user_not_found(self):
        """【登录接口】用户名不存在 → 401 & 用户不存在"""
        res = self.client.post(reverse('user-login'),
                               {'username': 'nobody', 'password': 'x'},
                               format='json')
        self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
        self.assertEqual(res.data['message'], '用户不存在')

    def test_login_wrong_password(self):
        """【登录接口】密码错误 → 401 & 密码错误"""
        res = self.client.post(reverse('user-login'),
                               {'username': 'alice', 'password': 'oops'},
                               format='json')
        self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
        self.assertEqual(res.data['message'], '密码错误')

    def test_login_missing_fields(self):
        """【登录接口】缺少用户名/密码 → 400 & 必填提示"""
        res = self.client.post(reverse('user-login'), {}, format='json')
        self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(res.data['message'], '用户名和密码必填')

    # ------------------------------------------------------------------
    # 2) /users/  —— 注册接口
    # ------------------------------------------------------------------

    def test_register_success(self):
        """【注册接口】完整信息注册成功 → 201"""
        payload = {
            'username': 'bob',
            'password': 'bobpw',
            'email': 'bob@mail.com',
            'phone': '13800000000',
            'role': '普通用户',
            'permission_level': 1
        }
        res = self.client.post(reverse('user-create'), payload, format='json')
        self.assertEqual(res.status_code, status.HTTP_201_CREATED)
        self.assertEqual(res.data['message'], 'User created successfully')
        self.assertTrue(User.objects.filter(username='bob').exists())

    def test_register_duplicate_username(self):
        """【注册接口】用户名已存在 → 400"""
        payload = {
            'username': 'alice',       # 与 setUp 中重复
            'password': 'newpw',
            'role': '普通用户',
            'permission_level': 1
        }
        res = self.client.post(reverse('user-create'), payload, format='json')
        self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertIn('username', str(res.data['message']))

    def test_register_missing_required(self):
        """【注册接口】缺少必填字段 → 400"""
        res = self.client.post(reverse('user-create'),
                               {'username': '', 'password': ''}, format='json')
        self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)

    # ------------------------------------------------------------------
    # 3) /users/all/  —— 找回密码第一步：获取所有用户
    # ------------------------------------------------------------------

    def test_get_all_users(self):
        """【用户列表接口】前端找回密码下拉框获取用户名 → 200 & 返回列表"""
        res = self.client.get(reverse('user-list'))
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertTrue(any(u['username'] == 'alice' for u in res.data))

    # ------------------------------------------------------------------
    # 4) /users/<id>/update/  —— 找回密码第二步：重设密码
    # ------------------------------------------------------------------

    def test_password_update_success(self):
        """【修改密码接口】带新密码 → 200 & 更新成功"""
        url = reverse('user-update', kwargs={'user_id': self.alice.user_id})
        res = self.client.put(url, {'password': 'newpass'}, format='json')
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(res.data['message'], 'User updated successfully')
        self.alice.refresh_from_db()
        self.assertEqual(self.alice.password, 'newpass')

    def test_password_update_user_not_found(self):
        """【修改密码接口】用户不存在 → 404"""
        url = reverse('user-update', kwargs={'user_id': 99999}) 
        res = self.client.put(url, {'password': 'x'}, format='json')
        self.assertEqual(res.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(res.data['message'], 'User not found')

    def test_password_update_no_fields(self):
        """【修改密码接口】请求体为空 → 400"""
        url = reverse('user-update', kwargs={'user_id': self.alice.user_id})
        res = self.client.put(url, {}, format='json')
        self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
